<?php

namespace app\forms\role;

use yii\db\Exception;
use app\models\Role;
use yii\web\HttpException;
use app\validators\PositiveInteger;

/**
 * 角色 编辑
 */
class UpdateForm extends BaseForm
{
    public $id;
    public $setDefault = 0;

    public function rules()
    {
        $rules = parent::rules();
        return array_merge($rules, [
            ['id', PositiveInteger::class],
            ['id', 'required', 'message' => 'ID不为空'],
            ['id', 'exist', 'targetClass' => Role::class],

            ['setDefault', 'boolean'],

            ['name', 'checkUnique'],
        ]);
    }

    public function checkUnique($attribute, $params)
    {
        $exist = Role::find()->select(['id'])->where(['and', ['name' => $this->$attribute], ['!=', 'id', $this->id]])->one();
        if ($exist)
            $this->addError($attribute, '名称已被占用');
    }

    /**
     * @param $param
     * @throws HttpException
     */
    public static function update($param)
    {
        $form = new self();
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {
            $attr = $form->getAttributes();
            unset($attr['id']);

            $role = Role::findOne($form['id']);
            $role->setAttributes($attr);
            $role->save(false);

            // 移除权限
            $role->removeItem();

            // 添加权限
            $role->addItem($form->item, $form->auth, $form->data);

            // 设置默认权限
            if ($form->setDefault) {
                $role->removeDefaultItem();
                $role->addDefaultItem($form->item, $form->auth, $form->data);
            }

            // casbin 操作

        } catch (Exception $e) {
            $form->serverError();
        }

        $form->updateOk();
    }
}